<script setup>
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { applyReturn, listPointRecord } from '@/api/pointRecord/pointRecord.js';
import useUserStore from '@/store/modules/user';

const userStore = useUserStore();
const orderId = ref(null);
const orderData = ref({});
const isSubmitting = ref(false);
const returnData = reactive({
  returnReason: '',
  logisticsCompany: '',
  logisticsNo: '',
  logisticsTime: ''
});

// 常见退货原因
const commonReasons = [
  '商品质量问题',
  '商品与描述不符',
  '收到商品破损',
  '不需要了',
  '尺寸不合适'
];

// 常见快递公司
const commonExpresses = [
  '顺丰快递',
  '圆通快递',
  '中通快递',
  '申通快递',
  '韵达快递',
  '邮政EMS'
];

const fetchOrderDetail = async (id) => {
  try {
    const res = await listPointRecord({ id });
    let item;
    const records = res.rows || res.data;
    if (Array.isArray(records)) {
      item = records.find(record => record.id == id);
    }
    if (!item) {
      item = (res.rows && res.rows[0]) || (res.data && res.data[0]) || res.data || res;
    }
    if (!item) return;
    orderData.value = {
      id: item.id,
      store: '积分商城',
      deal: '已发货', // 可根据实际状态调整
      totalPoints: item.pointsCost,
      goodsList: [
        {
          goodsUrl: item.productImage || '',
          title: item.productName,
          type: item.remark || '默认',
          deliveryTime: item.exchangeTime,
          price: String(item.exchangeQuantity > 0 ? Math.floor(item.pointsCost / item.exchangeQuantity) : item.pointsCost),
          number: item.exchangeQuantity || 1
        }
      ]
    };
  } catch (e) {
    console.error('获取订单详情失败', e);
  }
};

onLoad((options) => {
  if (options.id) {
    orderId.value = options.id;
    if (options.order) {
      // 解析并转换结构
      const raw = JSON.parse(decodeURIComponent(options.order));
      orderData.value = {
        id: raw.id,
        store: raw.store || '积分商城',
        deal: raw.deal || '已发货',
        totalPoints: raw.totalPoints,
        goodsList: raw.goodsList || []
      };
    } else {
      fetchOrderDetail(options.id);
    }
  }
});

const selectReason = (reason) => {
  if (returnData.returnReason === reason) {
    returnData.returnReason = '';
  } else {
    returnData.returnReason = reason;
  }
};

const selectExpress = (express) => {
  returnData.logisticsCompany = express;
};

const submitReturn = async () => {
  if (!returnData.returnReason.trim()) {
    uni.showToast({
      title: '请选择或输入退货原因',
      icon: 'none'
    });
    return;
  }

  if (!returnData.logisticsCompany.trim()) {
    uni.showToast({
      title: '请选择或输入快递公司',
      icon: 'none'
    });
    return;
  }

  if (!returnData.logisticsNo.trim()) {
    uni.showToast({
      title: '请输入快递单号',
      icon: 'none'
    });
    return;
  }

  isSubmitting.value = true;

  try {
    await applyReturn({
      id: orderId.value,
      userId: userStore.userId,
      ...returnData
    });

    uni.showToast({
      title: '退货申请已提交',
      icon: 'success'
    });

    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (e) {
    console.error(e);
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    });
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<template>
  <view class="container">
    <!-- 商品信息 -->
    <view class="product-section">
      <view class="section-title">退货商品</view>
      <view class="product-card" v-if="orderData.goodsList && orderData.goodsList.length > 0">
        <view class="order-header">
          <view class="store-name">{{ orderData.store || '积分商城' }}</view>
          <view class="order-status">{{ orderData.deal || '已发货' }}</view>
        </view>
        <view
            class="goods-item"
            v-for="(goods, index) in orderData.goodsList"
            :key="index"
        >
          <image
              class="product-image"
              :src="goods.goodsUrl || '/static/images/default-product.png'"
              mode="aspectFill"
          />
          <view class="product-info">
            <view class="product-name">{{ goods.title || '商品名称' }}</view>
            <view class="product-spec">{{ goods.type || '规格信息' }}</view>
            <view class="delivery-time" v-if="goods.deliveryTime">
              发货时间：{{ goods.deliveryTime }}
            </view>
            <view class="product-price">
              <text class="price">{{ goods.price || '0' }}</text>
              <text class="unit">积分</text>
              <text class="quantity">×{{ goods.number || '1' }}</text>
            </view>
          </view>
        </view>
        <!-- 显示总积分 -->
        <view class="total-points" v-if="orderData.totalPoints">
          <text class="total-label">共消耗积分：</text>
          <text class="total-value">{{ orderData.totalPoints }}</text>
          <text class="total-unit">积分</text>
        </view>
      </view>
    </view>

    <!-- 退货原因 -->
    <view class="form-section">
      <view class="section-title">
        退货原因
        <text class="required">*</text>
      </view>
      <view class="reason-tags">
        <view
            v-for="reason in commonReasons"
            :key="reason"
            class="reason-tag"
            :class="{ active: returnData.returnReason === reason }"
            @click="selectReason(reason)"
        >
          {{ reason }}
        </view>
      </view>
      <textarea
          v-model="returnData.returnReason"
          placeholder="请选择上述原因或详细描述退货原因"
          class="reason-input"
          maxlength="200"
      />
      <view class="char-count">{{ returnData.returnReason.length }}/200</view>
    </view>

    <!-- 物流信息 -->
    <view class="form-section">
      <view class="section-title">
        物流信息
        <text class="required">*</text>
      </view>

      <view class="form-item">
        <text class="label">快递公司</text>
        <view class="express-tags">
          <view
              v-for="express in commonExpresses"
              :key="express"
              class="express-tag"
              :class="{ active: returnData.logisticsCompany === express }"
              @click="selectExpress(express)"
          >
            {{ express }}
          </view>
        </view>
        <input
            v-model="returnData.logisticsCompany"
            placeholder="选择上述快递或手动输入"
            class="form-input"
        />
      </view>

      <view class="form-item">
        <text class="label">快递单号</text>
        <input
            v-model="returnData.logisticsNo"
            placeholder="请输入快递单号"
            class="form-input"
        />
      </view>

      <view class="form-item">
        <text class="label">寄出时间</text>
        <uni-datetime-picker
            type="datetime"
            v-model="returnData.logisticsTime"
            :clear-icon="false"
        >
          <view class="datetime-picker">
            <text v-if="returnData.logisticsTime">{{ returnData.logisticsTime }}</text>
            <text v-else class="placeholder">请选择寄出时间</text>
            <text class="arrow">></text>
          </view>
        </uni-datetime-picker>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <button
          @click="submitReturn"
          class="submit-btn"
          :disabled="isSubmitting"
      >
        {{ isSubmitting ? '提交中...' : '提交退货申请' }}
      </button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
  padding-bottom: 120rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;

  .required {
    color: #ff4d4f;
    margin-left: 4rpx;
  }
}

.product-section {
  margin-bottom: 30rpx;
}

.product-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.store-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.order-status {
  font-size: 24rpx;
  color: #1890ff;
  font-weight: 500;
}

.goods-item {
  display: flex;
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  background: #f0f0f0;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  margin-bottom: 8rpx;
}

.product-spec {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 4rpx;
}

.delivery-time {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.product-price {
  display: flex;
  align-items: baseline;

  .price {
    font-size: 28rpx;
    font-weight: 600;
    color: #ff6b35;
  }

  .unit {
    font-size: 22rpx;
    color: #ff6b35;
    margin-left: 4rpx;
    margin-right: 12rpx;
  }

  .quantity {
    font-size: 24rpx;
    color: #666;
  }
}

.total-points {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 16rpx;
  margin-top: 16rpx;
  text-align: right;

  .total-label {
    font-size: 26rpx;
    color: #666;
  }

  .total-value {
    font-size: 32rpx;
    font-weight: 600;
    color: #ff6b35;
    margin: 0 4rpx;
  }

  .total-unit {
    font-size: 24rpx;
    color: #ff6b35;
  }
}

.form-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.reason-tags, .express-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.reason-tag, .express-tag {
  padding: 12rpx 20rpx;
  background: #f8f9fa;
  border: 2rpx solid #e9ecef;
  border-radius: 20rpx;
  font-size: 26rpx;
  color: #666;
  transition: all 0.3s ease;

  &.active {
    background: #1890ff;
    border-color: #1890ff;
    color: #fff;
  }
}

.reason-input {
  width: 100%;
  min-height: 160rpx;
  padding: 16rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 8rpx;
  font-size: 28rpx;
  line-height: 1.5;
  background: #fafafa;
  box-sizing: border-box;

  &:focus {
    border-color: #1890ff;
    background: #fff;
  }
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.form-item {
  margin-bottom: 24rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 16rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fafafa;
  box-sizing: border-box;

  &:focus {
    border-color: #1890ff;
    background: #fff;
  }
}

.datetime-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 80rpx;
  padding: 0 16rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 8rpx;
  background: #fafafa;
  font-size: 28rpx;

  .placeholder {
    color: #999;
  }

  .arrow {
    color: #999;
    font-size: 24rpx;
  }
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #e9ecef;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(90deg, #1890ff 0%, #40a9ff 100%);
  color: #fff;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;

  &:disabled {
    background: #d9d9d9;
    color: #999;
  }
}
</style>
